function init() {
    document.addEventListener("deviceready", deviceReady, true);
    delete init;
}

function checkAuthentication() {
    if (localStorage.profile_id > 0) {
        wd_redirect('home.html');
    }
}
function hideError_2(id_append, num_milliseconds) {
    setTimeout(function() {
        $('#' + id_append + '').fadeOut('fast', function() {
            //            $('#'+id_append+'').show();
        });
        $('#' + id_append + '').removeClass('active').children().html('');
    }, num_milliseconds);
}
function hideError(id_append, item, num_milliseconds) {
    item.css("color", "red");
    setTimeout(function() {
        $('#' + id_append + '').fadeOut('fast', function() {
            //            $('#'+id_append+'').show();
        });
        $('#' + id_append + '').removeClass('active').children().html('');
    }, num_milliseconds);
}
function checkValidate(id_append) {
    var emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i,
            numericRegex = /^[0-9-]+$/;
    // error msg depends on the language
    var errormsg = new Array();
    errormsg[1] = 'The %s field is required.';
    errormsg[2] = 'Please input your %s';
    errormsg[3] = 'The %s field must contain only numbers.';
    errormsg[4] = 'This %s address is invalid.';
    errormsg[5] = '%s is too short. %s must be at least %number characters';
    errormsg[6] = 'Confirm password does not match password';
    errormsg[7] = 'The %s field must not exceed %number characters in length.';
    errormsg[8] = 'This %s is invalid.';
    //show msg
    var msgEr = '';
    var valueStr = '';
    var num_milliseconds = 3000;
    //check


    if ($('input[name="email"]').val() == '' || $('input[name="email"]').val() == 'E-mail') {
        msgEr = errormsg[2].replace('%s', 'email');
        $('#' + id_append + '').addClass('active').children().html(msgEr);
        hideError(id_append, $('input[name="email"]'), num_milliseconds);
        return false;
    } else if ($('input[name="email"]').val() != '') {
        valueStr = $('input[name="email"]').val();
        if (!emailRegex.test(valueStr)) {
            msgEr = errormsg[4].replace('%s', 'email');
            $('#' + id_append + '').addClass('active').children().html(msgEr);
            hideError(id_append, $('input[name="email"]'), num_milliseconds);
            return false;
        }
    }

    if ($('input[name="password"]').val() == '' || $('input[name="password"]').val() == 'Password') {
        msgEr = errormsg[2].replace('%s', 'password');
        $('#' + id_append + '').addClass('active').children().html(msgEr);
        hideError(id_append, $('input[name="password"]'), num_milliseconds);
        return false;
    }

    return true;
}
function handleLogin() {
    if (checkValidate('error-msg')) {
        var form = $("#login");
        //disable the button so we can't resubmit while we wait
        $("#submit", form).attr("disabled", "disabled");
        var u = $("#login-email", form).val();
        var p = $("#login-password", form).val();
        console.log("click");
        if (u != '' && p != '') {
            // fix pushtoken for testing in browser
            //var pushtoken = cordova.exec(success, fail, "PushToken", "getToken", types);
            //var udid= device.uuid;
            //alert(udid);
            //alert(pushtoken);
            udid = 'pushtoken';
            pushtoken = 'ABCDEF0123456789';
            $.post(localStorage.domain_app + "/webservice/login.php", {
                userEmail: u,
                password: p,
                pushtoken: pushtoken,
                udid: udid
            }, function(res) {
                if (res) {
                    var msgEr = '';
                    var num_milliseconds = 3000;
                    if (res == 4) {
                        msgEr = "This email has not been registered yet";
                        $('#error-msg').addClass('active').children().html(msgEr);
                        hideError_2('error-msg', num_milliseconds);
                        return false;
                    } else if (res == 2) {
                        $("#dialog-confirm").show();
                        $("#dialog-confirm").dialog({
                            resizable: false,
                            height: 200,
                            width: 300,
                            modal: true,
                            buttons: {
                                "Resend Confirmation": function() {
                                    var btn_resend= $(this);
                                     btn_resend.dialog("close");
                                    $.post(localStorage.domain_app + "/webservice/resendConfirmation.php", {
                                        userEmail: u

                                    }, function(res) {
                                         if(res.error==0){
                                             print_alert("An email with an activation link has been sent to your inbox. Please check your inbox and activate your account.");
                                         }
                                         return false;
                                    }, "json");

                                },
                                Cancel: function() {
                                    $(this).dialog("close");
                                     return false;
                                }
                            }
                        });

                    } else if (res == 3) {
                        msgEr = "The username and password do not match";
                        $('#error-msg').addClass('active').children().html(msgEr);
                        hideError_2('error-msg', num_milliseconds);
                        return false;
                    }else{
                         //store
                        localStorage.profile_id = res.results.profileID;
                        localStorage.userID = res.results.userID;
                        localStorage.token = res.results.token;
                        localStorage.firstName = res.results.firstName;
                        localStorage.lastName = res.results.lastName;
                        localStorage.userRole = res.results.userRole;
                        localStorage.email = res.results.email;
                        localStorage.facebook_token = "";
                        wd_redirect('home.html');
                    }


                    
                } else {
                    navigator.notification.alert("Your login failed", function() {
                    });
                }
                $("#submit").removeAttr("disabled");
            }, "json");
        } else {
            //Thanks Igor!
            navigator.notification.alert("You must enter a username and password", function() {
            });
            $("#submit").removeAttr("disabled");
        }
    }

    return false;
}
function onConfirmLogin(button) {
    if (button == 1) {
        FB.init({appId: "470782169676577", nativeInterface: CDV.FB, useCachedDialogs: false});

        FB.login(
                function(response) {
                    // console.log(response);
                    if (response.status == 'connected') {
                        if (typeof(Storage) !== "undefined")
                        {
                            $('.wd-loading').show();
                            localStorage.facebook_token = response.authResponse.accessToken;
                            FB.api("/me", function(response_me) {
                                //console.log( response_me);
                                if (response_me.error) {

                                    alert(JSON.stringify(response_me.error));
                                    wd_redirect('login.html');
                                } else {
                                    sessionStorage.facebook_first_name = response_me.first_name;
                                    sessionStorage.facebook_last_name = response_me.last_name;
                                    sessionStorage.facebook_email = response_me.email;
                                    localStorage.facebook_id = response_me.id;
                                    udid = 'pushtoken';
                                    pushtoken = 'ABCDEF0123456789';
                                    $.post(localStorage.domain_app + "/webservice/facebook/loginFacebook.php", {
                                        facebook_id: localStorage.facebook_id,
                                        firstname: sessionStorage.facebook_first_name,
                                        lastname: sessionStorage.facebook_last_name,
                                        email: sessionStorage.facebook_email,
                                        pushtoken: pushtoken,
                                        udid: udid
                                    }, function(res) {
                                        //console.log(res);
                                        sessionStorage.clear();
                                        if (res.error == 1) {

                                            print_alert(res.msg);
                                            localStorage.clear();
                                            wd_redirect('login.html');
                                        } else {
                                            localStorage.profile_id = res.profileID;
                                            localStorage.userID = res.userID;
                                            localStorage.token = res.token;
                                            localStorage.firstName = res.firstName;
                                            localStorage.lastName = res.lastName;
                                            localStorage.userRole = res.userRole;
                                            localStorage.email = res.email;
                                            is_the_first_login_facebook = res.is_the_first_login_facebook;
                                            //insert user's friend in table guest

                                            if (is_the_first_login_facebook) {
                                                $.post(localStorage.domain_app + "/webservice/facebook/updateFriendList.php", {
                                                    access_token: localStorage.facebook_token,
                                                    facebook_id: localStorage.facebook_id,
                                                    user_id: localStorage.userID,
                                                }, function(result_2) {

                                                    wd_redirect('signUpFacebook.html');

                                                }, "json");

                                            } else {
                                                wd_redirect('home.html');
                                            }
                                        }
                                    }, "json");
                                }
                            });


                        } else {
                            return false;
                        }
                    } else {
                        print_alert("Your Facebook login failed");
                        wd_redirect('login.html');
                    }
                },
                {scope: "email,xmpp_login"}
        );
    } else {
        return false;
    }
}
function eventClickEnter(e) {
    if (e.keyCode == 13) {
        handleLogin();
    }
}
$(function() {
    if (typeof(Storage) !== "undefined")
    {
        if (!localStorage.domain_app) {
            localStorage.domain_app = "http://weddinghelperapp.com";
        }
    }
    checkAuthentication();

    $(".btn-submit-login-fb").click(function() {
        // process the confirmation dialog result

        print_confirm("Facebook \n Wedding helper would like to access your profile, email and chat as well as your friend list?", onConfirmLogin);

    });

    $("#submit").click(function() {
        handleLogin();
    });

    $('#login-password').focus(function() {
        $(this).css("color", "#ffffff");
        if (this.value == this.defaultValue) {
            $(this).val("");
            $(this).val('').prop('type', 'password');
        } else if (this.value != this.defaultValue) {

            this.select();
        }

    })
            .blur(function() {
        if ($(this).val() == '') {
            $(this).val($(this).attr('rel')).prop('type', 'text');
        }
    });

    $('input[name="email"]').focus(function() {
        $(this).css("color", "#ffffff");
        if (this.value == "E-mail") {
            this.value = '';
        }
        if (this.value != "E-mail") {
            this.select();
        }
    }).blur(function() {
        if (jQuery.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });
})